# -*- coding: utf-8 -*-

import blog
from flask import Flask, request, render_template, jsonify
from werkzeug import secure_filename
import os

app = Flask(__name__)

ARGS_ERROR = {
    "code": -1,
    "message": "参数错误"
    }

# API部分

@app.route("/api/__init", methods=["POST"])
def init():
    username, password = request.form.get("username", None), request.form.get("password", None)
    if username is not None and password is not None:
        if not request.form.get("force", None):
            return jsonify(blog.init_blog(app, admin=username, pwd=password))
        else:
            return jsonify(blog.init_blog(app, admin=username, pwd=password, force=True))
    else:
        return jsonify(ARGS_ERROR)

@app.route("/api/login", methods=["POST"])
def api_login():
    username, password = request.form.get("username", None), request.form.get("password", None)
    if username is not None and password is not None:
        return jsonify(blog.login(username, password))
    else:
        return jsonify(ARGS_ERROR)

@app.route("/api/article.list")
def article_list():
    page_no = request.args.get("page_no", 1)
    page_size = request.args.get("page_size", 20)
    return jsonify(blog.article_list(page_no, page_size))

@app.route("/api/article.post", methods=["POST"])
def article_post():
    args = { i:request.form[i] for i in request.form }
    try:
        return jsonify(blog.article_post(args, args["key"]))
    except KeyError:
        return jsonify(ARGS_ERROR)

@app.route("/api/article.delete")
def article_delete():
    article_id, key = request.args.get("article_id"), request.args.get("key")
    if article_id is not None and key is not None:
        return jsonify(blog.article_delete(article_id, key))
    else:
        return jsonify(ARGS_ERROR)

@app.route("/api/article.detail")
@app.route("/api/article.detail/<int:article_id>")
def article_detail(article_id=None):
    if article_id:
        return jsonify(blog.article_detail(article_id))
    else:
        article_id = request.args.get("article_id")
        if article_id:
            return jsonify(blog.article_detail(article_id))
        else:
            return jsonify(ARGS_ERROR)

# 超级无敌的简陋的要死的前端测试部分

@app.route("/")
@app.route("/<int:page>")
def index(page=1):
    r = blog.article_list(page)
    return render_template("index.html", aricles=r["results"], page=page, total_page=r["total_page"])

@app.route("/article.post", methods=["GET", "POST"])
def post():
    if request.method == "GET":
        if request.cookies.get("key"):
            if blog.check_key(request.cookies.get("key")):
                return render_template("post.html")
            else:
                return '<a href="/login">滚去登录!</a>'
        else:
            return '<a href="/login">滚去登录!</a>'
    else:
        if request.cookies.get("key"):
            r = blog.article_post(
                {
                    "title": request.forms.get("title"),
                    "context": request.forms.get("context")
                },
                request.cookies.get("key"))
            if r["code"] == 0:
                return '<a href="/">OK!</a>'
            else:
                return '<a href="/login">滚去登录!</a>'
        else:
            return '<a href="/login">滚去登录!</a>'

@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    else:
        r = blog.login(request.forms.get("username"), request.forms.get("password"))
        if r["code"] == 0:
            resp = make_response('<a href="/">OK!</a>')
            resp.set_cookie("key", r["key"])
            return resp
        else:
            return '<a href="/">Go to home</a>'

if __name__ == "__main__":
    blog.init(app)
    app.run(debug=True)